﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeBackup.Code
{

    public delegate void EventMessage(string File, bool isTrue, string error);
    public class DownLoadFile
    {

        private EventMessage @event;
        string savename=string.Empty;   

       public async Task LoadAsync(string FileName,string saveName, EventMessage eventHandler)
        {
            this.@event = eventHandler;
            this.savename = saveName;
            // 文件下载的 API URL
            string url = $"{ini.Api}/Api/edi/Load?FileName={FileName}";
            // 指定文件保存路径
            string filePath = Path.Combine(ini.SaveDirec, saveName);

            // 下载文件
            await DownloadFileAsync(url, filePath);
        }


        async Task DownloadFileAsync(string url, string filePath)
        {
            using (HttpClient client = new HttpClient())
            {
                bool b = true;
                string mess = string.Empty; 
                try
                {
                    // 发送 GET 请求以下载文件
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容为字节流
                    byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

                    // 将字节流写入本地文件
                    await System.IO.File.WriteAllBytesAsync(filePath, fileBytes);

                    Console.WriteLine("File download completed.");
                }
                catch (Exception ex)
                {
                    b=false;
                    mess=$"An error occurred: {ex.Message}";
                }
                finally
                {
                    @event?.Invoke(filePath,b, mess);
                }
            }
        }

    }




}
